import { handleActions } from "redux-actions";
import { add_product_to_cart_success, delete_product_from_cart_success, get_product_from_cart_success, modify_cart_mount_success } from "../actions/cart";

const initState = []

const handleAddProducts = (state, action) => {
  // console.log(JSON.parse(JSON.stringify(state)))
  // 拷贝原有的购物车数据
  const newState = JSON.parse(JSON.stringify(state))
  const product = newState.find(product => product.id === action.payload.id)
  parseInt(product.count)
  if(product){
    console.log(product.count)
    product.count = product.count + 1
  } else {
    newState.push(action.payload)
  }
  return newState
}
 // 将服务器端返回的数据同步到本地的购物车中
const handleGetProductsfromCart = (state, action) => action.payload
const handleDeleteCartsProducts = (state, action) => {
  const newState = JSON.parse(JSON.stringify(state))
  newState.splice(action.payload, 1)
  return newState
}
const handleModifyCartsMount = (state, action) => {
  const newState = JSON.parse(JSON.stringify(state))
  const product = newState.find(product => product.id === action.payload.id)
  product.count = action.payload.count
  return newState
}
const cartReducer = handleActions({
  [add_product_to_cart_success]: handleAddProducts,
  // 将服务器端返回的数据同步到本地的购物车中
  [get_product_from_cart_success]: handleGetProductsfromCart,
  [delete_product_from_cart_success] : handleDeleteCartsProducts,
  // 更新购物车中的数量
  [modify_cart_mount_success]: handleModifyCartsMount
}, initState)


export default cartReducer 